package controller;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.StringTokenizer;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.Domain;
import data.Data;

@SuppressWarnings("serial")
public class SameIpServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		response.setHeader( "Cache-Control", "public, max-age=86400");
		response.setHeader( "Expires", new Date(Calendar.getInstance().getTime().getTime()+24*60*60*1000).toGMTString());
		response.setCharacterEncoding("utf-8");
		String path = ((HttpServletRequest)request).getRequestURI();
		
		StringTokenizer st = new StringTokenizer( path,"/");
        int count = st.countTokens(); 
        
        if(count!=2)
        {
        	response.getWriter().println("Bad request : "+request.getRequestURI());
        	response.getWriter().close();
        	return ;
        }

		// skip one token /sites/gooogle.com (remove sites)
		st.nextToken();
		String name = URLDecoder.decode(st.nextToken(),"UTF-8");
		
		PersistenceManager psm = Data.get().getPersistenceManager();
		
		Query query = psm.newQuery(Domain.class);
		query.setFilter("ip=='"+name+"'");
		query.setRange(0,20);
		List<Domain> listDomain = (List<Domain>) query.execute();
		request.setAttribute("listDomain", listDomain);
		request.setAttribute("name", name);
		try {
			request.getRequestDispatcher("/same-ip.jsp").forward(request, response);
		} catch (Exception e) {
			// TODO: handle exception
		}

	}
}
